<template>
	<div>
		<header class="header">
			<el-button @click="articleItemClass.cancel()">取消</el-button>
			<el-button type="primary" :icon="Position" @click="articleItemClass.submitForm()">保存</el-button>
		</header>
		<section class="article-item">
			<el-form ref="ruleFormRef" :model="articleItemClass.ruleForm.value" :rules="articleItemClass.rules" label-width="120px">
				<el-form-item label="标题" prop="title">
					<el-input v-model="articleItemClass.ruleForm.value.title" />
				</el-form-item>
				<el-form-item label="摘要" prop="abstract">
					<el-input v-model="articleItemClass.ruleForm.value.abstract" />
				</el-form-item>
				<el-form-item label="内容" prop="content">
					<div style="width: 100%">
						<!-- 此处注意写法v-model:content -->
						<QuillEditor
							ref="myQuillEditor"
							theme="snow"
							v-model:content="articleItemClass.ruleForm.value.content"
							:options="data.editorOption"
							contentType="html"
							@update:content="setValue()"
						/>
						<!-- 使用自定义图片上传 -->
						<input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" />
					</div>
					<el-button type="primary" link style="margin-top: 10px" @click="visible = true">内容展示</el-button>
				</el-form-item>
				<el-form-item label="分类" prop="type">
					<el-select v-model="articleItemClass.ruleForm.value.type" clearable>
						<el-option v-for="item in articleItemClass.typeList.value" :key="item.id" :value="item.title" :label="item.title" />
					</el-select>
				</el-form-item>
				<el-form-item label="标签" prop="tag">
					<el-select v-model="articleItemClass.ruleForm.value.tag" clearable multiple>
						<el-option
							v-for="item in articleItemClass.tagList.value"
							:key="item.id"
							:value="item.tagName"
							:label="item.tagName"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="封面" prop="img">
					<el-upload
						class="avatar-uploader"
						action="http://ikun-pro-ui.fun:3000/upload-file/image"
						:show-file-list="false"
						:on-success="articleItemClass.handleAvatarSuccess"
					>
						<img
							v-if="articleItemClass.ruleForm.value.img"
							:src="`${'http://ikun-pro-ui.fun:3000/static/'}${articleItemClass.ruleForm.value.img}`"
							class="avatar"
						/>
						<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
					</el-upload>
				</el-form-item>
			</el-form>
			<CommonDrawer v-model="visible" :show-close="false">
				<template #header> 内容展示 </template>
				<template #default>
					<div v-html="articleItemClass.ruleForm.value.content" />
				</template>
				<template #footer>
					<el-button @click="visible = !visible" type="primary">确定</el-button>
				</template>
			</CommonDrawer>
		</section>
	</div>
</template>

<script lang="ts" setup>
import { Plus, Position } from '@element-plus/icons-vue'
import { ArticleItemClass } from './controller'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { reactive, onMounted, ref, toRaw, watch } from 'vue'
import { ArticeApi } from '../api'
import { ElMessage } from 'element-plus'
const ruleFormRef = ref()
const visible = ref<boolean>(false)
let articleItemClass = new ArticleItemClass(ruleFormRef)
const props = defineProps<{
	value: any
	readOnly: boolean
}>()
const emit = defineEmits(['updateValue'])
const myQuillEditor = ref()
// 只监听一次 通过watch监听回显
const stopWatch = watch(
	() => articleItemClass.ruleForm.value.content,
	val => {
		if (myQuillEditor.value) {
			toRaw(myQuillEditor.value).setHTML(val)
		}
		// 停止监听
		stopWatch()
	},
	{ deep: true }
)
const fileBtn = ref()
const data = reactive({
	content: '',
	editorOption: {
		readOnly: props.readOnly ?? false,
		modules: {
			toolbar: [
				['bold', 'italic', 'underline', 'strike'],
				[{ size: ['small', false, 'large', 'huge'] }],
				[{ font: [] }],
				[{ align: [] }],
				[{ list: 'ordered' }, { list: 'bullet' }],
				[{ indent: '-1' }, { indent: '+1' }],
				[{ header: 1 }, { header: 2 }],
				['image'],
				[{ direction: 'rtl' }],
				[{ color: [] }, { background: [] }]
			]
		},
		placeholder: '请输入内容...'
	}
})
const imgHandler = (state: any) => {
	if (state) {
		fileBtn.value.click()
	}
}
// 抛出更改内容，此处避免出错直接使用文档提供的getHTML方法
const setValue = () => {
	const text = toRaw(myQuillEditor.value).getHTML()
	emit('updateValue', text)
}
const handleUpload = (e: any) => {
	const files = Array.prototype.slice.call(e.target.files)
	if (!files) {
		return
	}
	const formdata = new FormData()
	formdata.append('file', files[0])
	ArticeApi.upload(formdata).subscribe(
		(res: any) => {
			const quill = toRaw(myQuillEditor.value).getQuill()
			const length = quill.getSelection().index
			// 插入图片，res为服务器返回的图片链接地址
			quill.insertEmbed(length, 'image', `${'http://ikun-pro-ui.fun:3000/static/'}${res.filename}`)
			// 调整光标到最后
			quill.setSelection(length + 1)
		},
		() => {
			ElMessage.warning
		}
	)
}
// 初始化编辑器
onMounted(() => {
	const quill = toRaw(myQuillEditor.value).getQuill()
	if (myQuillEditor.value) {
		quill.getModule('toolbar').addHandler('image', imgHandler)
	}
	toRaw(myQuillEditor.value).setHTML(articleItemClass.ruleForm.value.content ?? '')
})
</script>
<style lang="scss" src="./index.scss"></style>
<style scoped lang="scss">
// 调整样式
:deep(.ql-editor) {
	min-height: 180px;
}
:deep(.ql-formats) {
	height: 21px;
	line-height: 21px;
}
</style>
